package com.kichina.parking.upstream;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kichina.parking.exception.extend.JsonParseException;
import com.kichina.parking.service.logic.bean.ChargingRulesRecord;
import com.kichina.parking.service.logic.service.ChargingRulesRecordService;
import com.kichina.parking.utils.JsonToEntityUtil;
import com.kichina.parking.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @author Surging
 * @version 1.0
 * @ClassName MonthPayUpstreamHandler
 * @date 2022-09-14 20:03
 * @desc 固定车收费规则
 */
@Component
@Slf4j
public class Parking10MonthPayRuleUpstreamHandler {

    private final ChargingRulesRecordService chargingRulesRecordService;

    public Parking10MonthPayRuleUpstreamHandler(ChargingRulesRecordService chargingRulesRecordService) {
        this.chargingRulesRecordService = chargingRulesRecordService;
    }

    /**
     * @param jsonObject 数据实体
     * @author Surging
     * @Description 车场新增或者修改固定车收费规则后上传信息业务处理层
     * (上传方式：立即上传)
     * @Return void
     * @date 20:53 2022-09-15
     **/
    public void recordParkingMonthPayRuleUpstream(JSONObject jsonObject) throws JsonParseException {

        ChargingRulesRecord chargingRulesRecord;
        try {
            chargingRulesRecord = JsonToEntityUtil.jsonToEntity(jsonObject, ChargingRulesRecord.class);
            LambdaQueryWrapper<ChargingRulesRecord> eq = new QueryWrapper<ChargingRulesRecord>().lambda()
                    .eq(ChargingRulesRecord::getParkid, chargingRulesRecord.getParkid())
                    .eq(ChargingRulesRecord::getRuleId, chargingRulesRecord.getRuleId());
            List<ChargingRulesRecord> chargingRulesRecordList = chargingRulesRecordService.list(eq);
            if (CollectionUtils.isNotEmpty(chargingRulesRecordList)){
                //更新
                chargingRulesRecord.setUpdateTime(new Date());
                chargingRulesRecordService.update(chargingRulesRecord, eq);
            }else {
                //添加
                chargingRulesRecord.setChargingRulesRecordId(UUIDUtil.getUUID());
                chargingRulesRecord.setUpdateTime(new Date());
                //原实体有createTime字段，serviceCreateTime作区分
                chargingRulesRecord.setCreateTime(new Date());
                chargingRulesRecordService.save(chargingRulesRecord);
            }
        } catch (ParseException e) {
            log.error("数据格式不合法，解析失败");
            throw new JsonParseException("数据格式不合法，解析失败");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
